<template>
    <el-card shadow="never">
        <store-progress v-model="step" :type="2" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="10" />
            </div>
            <div class="line"></div>
            <div v-show="step === 1" class="msg">
                <div class="title">服务购买</div>
                <el-form
                    ref="storeBaseFormRef"
                    :model="storeBaseForm"
                    :rules="storeBaseFormRules"
                    label-width="auto"
                    :disabled="type == 'look'">
                    <el-form-item label="服务应用" prop="service_application">
                        <el-radio-group
                            v-model="storeBaseForm.service_application"
                            :disabled="query.shop_id"
                            @change="changeService">
                            <el-radio :label="1" size="small"> 应用服务 </el-radio>
                            <el-radio :label="2" size="small"> 暂不购买 </el-radio>
                        </el-radio-group>
                        <div v-show="storeBaseForm.service_application == 1" class="formTips">
                            <span>
                                选择应用该服务，同意签署
                                <span class="toAgreement" @click="toAgreement">《客易达数据安全隐私协议》</span>
                                文件。客易达将自动同步来自快手店铺的订单、商品、用户数据。
                            </span>
                        </div>
                        <div v-show="storeBaseForm.service_application == 2" class="formTips">
                            选择暂不购买，无需店铺授权。可通过快手店铺后台下载订单、商品数据、导入系统。
                        </div>
                    </el-form-item>
                    <el-form-item v-show="storeBaseForm.service_application == 1" label="线路" prop="ks_line">
                        <el-select v-model="storeBaseForm.ks_line" :disabled="query.shop_id">
                            <el-option
                                v-for="item in lineList"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"></el-option>
                        </el-select>
                        <div v-show="storeBaseForm.service_application == 1" class="sync">
                            <div class="sync-img">
                                <div class="upload-file-box">
                                    <el-image-viewer
                                        v-if="imgSow"
                                        class="img-detail"
                                        :url-list="bigImg"
                                        @close="closeImg">
                                    </el-image-viewer>
                                    <el-image
                                        class="img-detail"
                                        src="https://static.scrm.keyid.cn/assets/images/web-pc/kuaishou_shop.png"
                                        fit="cover">
                                    </el-image>
                                    <el-icon class="open-img" :style="{ fontSize: '18px' }" @click="openImg">
                                        <ZoomIn />
                                    </el-icon>
                                </div>
                            </div>
                            <div v-show="!query.shop_id" class="sync-title">
                                <el-button type="primary" @click="goShop"> 去购买 </el-button>
                                <div class="title-detail">请点击“去购买”，在打开的网页购买应用</div>
                            </div>
                        </div>
                    </el-form-item>
                    <div class="title">店铺基本信息</div>
                    <el-form-item v-if="type == 'edit' || type == 'look'" label="客易达店铺ID" prop="retail_shop_id">
                        <el-input v-model.trim="storeBaseForm.retail_shop_id" disabled />
                    </el-form-item>
                    <el-form-item
                        :label="storeBaseForm.service_application == 1 ? '小店授权ID' : '快手小店ID'"
                        prop="external_shop_id">
                        <div v-show="storeBaseForm.service_application == 1">
                            <span v-if="!storeBaseForm.external_shop_id">
                                --
                                <span class="go-auth" @click="goAuth">去授权</span>
                            </span>
                            <span v-else>
                                <span>{{ storeBaseForm.external_shop_id }}</span>
                                <span v-show="query.shop_id && state == 2" class="go-auth" @click="goAuth">
                                    重新授权
                                </span>
                            </span>
                            <div v-show="existed" class="color-tips">该店铺已存在</div>
                            <!--state==2取消授权isSuccess未查询到授权信息-->
                            <div v-show="isSuccess && !isCancel && state != 2" class="color-tips">未查询到授权信息</div>
                            <div v-show="query.shop_id && state == 2" class="color-tips">
                                该店铺已取消授权，若要正常使用服务，请重新完成授权
                            </div>
                            <div v-show="query.shop_id && existed" class="color-tips">
                                只能授权同一家店铺，若要授权新店铺请重新创建店铺
                            </div>
                        </div>
                        <div v-show="storeBaseForm.service_application == 2" class="withTips">
                            <el-input
                                v-model.trim="storeBaseForm.external_shop_id"
                                :disabled="query.shop_id"
                                placeholder="请输入快手小店ID"
                                @blur="checkId" />
                            <span @click="toCheck">如何查看快手小店ID</span>
                        </div>
                        <div v-show="cust_existed && storeBaseForm.service_application == 2" class="color-tips">
                            该店铺已存在
                        </div>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="name">
                        <div v-show="storeBaseForm.service_application == 1">
                            <span v-if="!storeBaseForm.name">
                                --
                                <span class="go-auth" @click="goAuth">去授权</span>
                            </span>
                            <span v-else>
                                <span>{{ storeBaseForm.name }}</span>
                                <span v-show="query.shop_id && state == 2" class="go-auth" @click="goAuth">
                                    重新授权
                                </span>
                            </span>
                        </div>
                        <el-input
                            v-if="storeBaseForm.service_application == 2"
                            v-model="storeBaseForm.name"
                            placeholder="请输入店铺名称" />
                    </el-form-item>
                    <el-form-item label="店铺LOGO" prop="logo">
                        <store-upload v-model="storeBaseForm.logo" />
                    </el-form-item>
                    <div v-show="storeBaseForm.service_application == 1">
                        <div class="title">订单解析</div>
                        <el-form-item label="解析方式" prop="decode_way">
                            <el-radio-group v-model="storeBaseForm.decode_way">
                                <el-radio :label="1" size="small"> 实时解析 </el-radio>
                                <el-radio :label="2" size="small"> 周期解析 </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <div class="formTips tips">
                            <div class="tips_title">说明</div>
                            <div>1、根据平台限制，每日解析额度存在上限，解析额度不得累加，每天0点清零。</div>
                            <div>2、每日解析额度达到上限之后或当日已结束，将停止解析。</div>
                            <div>3、按照快手平台订单解析的限制，客易达SCRM将最大程度为您提供订单解析服务。</div>
                        </div>
                    </div>
                </el-form>
            </div>

            <div v-show="step === 2" class="finishBox">
                <el-icon :style="{ fontSize: '60px' }" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">{{ `店铺${!!query.shop_id ? '编辑' : '创建'}成功` }}</div>
                <div class="tag">您的客易达店铺ID为：{{ shop_id }} <span @click="copy(shop_id)">复制</span></div>
                <div v-if="open_platform == 1" class="tag">
                    请前往设置与开发去开启开发者功能 <span @click="toSetting">去配置</span>
                </div>
            </div>
        </div>
    </el-card>

    <div class="footer_button">
        <el-button v-if="step === 1" type="primary" @click="nextStep"> 下一步 </el-button>
        <el-button v-if="step === 2" type="primary" @click="done"> 完成 </el-button>
    </div>

    <el-dialog v-model="changePackage" title="企业专属顾问" width="25%" center>
        <div class="qwQrCode" style="text-align: center">
            <img src="https://static.scrm.keyid.cn/assets/images/global/service.png" alt="" />
        </div>
        <p style="text-align: center">扫码添加企微顾问，开通使用！</p>
    </el-dialog>

    <Dialog :app-dialog="appDialog">
        <div class="auth-tips">请在新窗口中完成快手小店的授权，授权成功后请点击“授权成功”</div>
    </Dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import {
    ksShopConfig,
    addStore,
    editStore,
    ksAuthUrl,
    authResult,
    getStoreDetail,
    checkStore
} from '@/api/ecommerce/storeManage';
import { commonLinkList } from '@/api/channel/authconfig';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import storeUpload from '../components/storeUpload.vue';
import lodash from 'lodash';
import useClipboard from 'vue-clipboard3';
import Dialog from '@/components/Dialog.vue';
import type { FormInstance, FormRules } from 'element-plus';

const route = useRoute();
const router = useRouter();
const { toClipboard } = useClipboard();
const lineList = ref([]);
const bigImg = ref([]);
const storeBaseFormRef = ref<FormInstance>();
const step = ref<number>(1); // 步骤数
const shop_id = ref<string | number>('');
const open_platform = ref<string | number>('');
const shop_link = ref();
const changePackage = ref(false);
const existed = ref(false);
const isSuccess = ref(false);
const isCancel = ref(false);
const cust_existed = ref(false);
const state = ref();
const authId = ref(0);
const query = reactive<any>({
    source: '',
    shop_id: ''
});
// 页面类型：新增、编辑、查看
const { type } = route.query;
const imgSow = ref(false);
type storeBaseFormType = {
    name: string;
    external_shop_id: string;
    service_application: number;
    ks_line: number;
    decode_way: number;
    logo: string;
    retail_shop_id: string;
};
const storeBaseForm = reactive<storeBaseFormType>({
    name: '',
    service_application: 1, //服务应用 1-应用服务 2-暂不购买
    ks_line: 1, //线路
    decode_way: 1, //解析方式 1-周期解密 2-实时
    external_shop_id: '',
    logo: '',
    retail_shop_id: '' // 客易达店铺ID
});

const storeBaseFormRules = reactive<FormRules>({
    service_application: [{ required: true, message: '请选择服务应用', trigger: 'change' }],
    ks_line: [{ required: true, message: '请选择线路', trigger: 'change' }],
    external_shop_id: [
        {
            required: true,
            message: storeBaseForm.service_application == 1 ? '请输入小店授权ID' : '请输入快手小店ID',
            trigger: 'change'
        }
    ],
    decode_way: [{ required: true, message: '请选择解析方式', trigger: 'change' }],
    name: [{ required: true, message: '请输入店铺名称', trigger: 'change' }],
    logo: [{ required: true, message: '请上传店铺logo', trigger: 'change' }]
});
// 取消
const cancelHandel = (): void => {
    isCancel.value = true;
    getResult();
};
//确定
const submitHandel = (): void => {
    isCancel.value = false;
    getResult();
};
//获取授权结果
const getResult = () => {
    appDialog.visible = false;
    authResult({ shop_id: query.shop_id ? query.shop_id : 0, authId: authId.value }).then((res: any) => {
        if (res.openId != '') {
            storeBaseForm.external_shop_id = res.openId;
            storeBaseForm.name = res.shopName;
        }
        existed.value = res.existed;
        isSuccess.value = res.openId == '' ? true : false;
        state.value = res.state;
    });
};
const appDialog = reactive({
    visible: false,
    title: '提示',
    width: '450px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '授权失败，稍后重试',
    submitText: '授权成功'
});
//切换服务应用
const changeService = () => {
    storeBaseForm.external_shop_id = '';
    storeBaseForm.name = '';
    storeBaseForm.logo = '';
    storeBaseFormRef.value.clearValidate();
};
const nextStep = async (): Promise<void> => {
    // 查看店铺下一步时不调用接口
    if (type == 'look') {
        step.value++;
        return;
    }
    if (!storeBaseFormRef.value) return;
    if (existed.value || cust_existed.value) {
        return;
    }
    if (state.value == 2 && storeBaseForm.service_application == 1) {
        return;
    }
    if (storeBaseForm.service_application == 2) {
        storeBaseFormRules.ks_line[0].required = false;
        storeBaseFormRules.decode_way[0].required = false;
    }
    await storeBaseFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            let flag = false;
            if (query.shop_id) {
                flag = await editStoreCom();
            } else {
                flag = await addStoreCom();
            }
            if (flag) {
                step.value++;
            }
        }
    });
};
const checkId = () => {
    const params = {
        source: query.source,
        external_shop_id: storeBaseForm.external_shop_id
    };
    checkStore(params).then((res: any) => {
        cust_existed.value = res.shop_is_exists == 1 ? true : false;
    });
};
//方法图片
const openImg = () => {
    bigImg.value = ['https://static.scrm.keyid.cn/assets/images/web-pc/kuaishou_shop.png'];
    imgSow.value = true;
};
//关闭方法图片
const closeImg = () => {
    imgSow.value = false;
    bigImg.value = [];
};
//去授权
const goAuth = () => {
    ksAuthUrl({ shop_id: query.shop_id ? query.shop_id : 0 }).then((res: any) => {
        authId.value = res.authId;
        appDialog.visible = true;
        window.open(res.url);
    });
};
const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};

const toCheck = () => {
    window.open('/kuaishou-store');
};

const addStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const extr = {
        source: query.source
    };
    params = Object.assign({}, params, extr);
    const { shop_id: shop_id_, open_platform: open_platform_ } = await addStore(params);
    if (shop_id_) {
        shop_id.value = shop_id_?.toString();
        open_platform.value = open_platform_;
        return true;
    } else {
        return false;
    }
};

const editStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const extr = {
        source: query.source,
        shop_id: query.shop_id
    };
    params = Object.assign({}, params, extr);
    shop_id.value = storeBaseForm.retail_shop_id;
    return (await editStore(params)) as boolean;
};

const copy = async (val: string | number) => {
    try {
        await toClipboard(val.toString());
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
const toSetting = () => {
    const path = '/channelconfig/developConfiguration/basicConfiguration';
    router.push(path);
};

const toAgreement = () => {
    const path = '/agreement?show=privacyAgreement';
    window.open(path, '_blank');
};

const height = computed(() => {
    const clientHeight = document.documentElement.clientHeight;
    return `${clientHeight - 380}px`;
});

const getDetailInfo = async (query_shop_id: string) => {
    const {
        name: name = '',
        external_shop_id: external_shop_id = '',
        logo: logo = '',
        retail_shop_config: {
            decode_way: decode_way = 1,
            service_application: service_application = 1,
            ks_line: ks_line = 1
        },
        retail_shop_id
    } = await getStoreDetail({ retail_shop_id: query_shop_id });
    storeBaseForm.name = name;
    storeBaseForm.external_shop_id = external_shop_id;
    storeBaseForm.decode_way = decode_way;
    storeBaseForm.logo = logo;
    storeBaseForm.service_application = service_application;
    storeBaseForm.ks_line = ks_line;
    storeBaseForm.retail_shop_id = retail_shop_id;
    shop_id.value = retail_shop_id;
    if (service_application == 1) {
        getResult();
    }
};

const getShopConfig = async () => {
    ksShopConfig().then((res: any) => {
        lineList.value = res.ks_line_list;
        storeBaseForm.ks_line = res.ks_line_list[0].value;
    });
};

const getShopLink = async () => {
    commonLinkList({ codes: ['kuaishou_buy_app'] }).then((res: any) => {
        shop_link.value = res.kuaishou_buy_app.url;
    });
};
//去购买
const goShop = () => {
    window.open(shop_link.value);
};
const init = async () => {
    query.source = Number(route.query.source);
    query.shop_id = route.query.shop_id;
    if (route.query?.shop_id) {
        const shop_id = route.query.shop_id;
        await getDetailInfo(shop_id as string);
    }
    await getShopConfig();
    await getShopLink();
};
//清空上传图片组件的校验
watch(
    () => storeBaseForm.logo,
    val => {
        storeBaseFormRef.value.clearValidate('logo');
    }
);
//清空店铺名称的校验
watch(
    () => storeBaseForm.name,
    val => {
        storeBaseFormRef.value.clearValidate('name');
    }
);
//清空店铺ID的校验
watch(
    () => storeBaseForm.external_shop_id,
    val => {
        storeBaseFormRef.value.clearValidate('external_shop_id');
    }
);
onMounted(async () => {
    await init();
});
</script>
<style scoped lang="scss">
.content {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 339px);

    .withTips {
        display: flex;
        align-items: center;

        span {
            white-space: nowrap;
            text-indent: 12px;
            font-size: 12px;
            color: #ff6b00;

            &:hover {
                color: #f99547;
                cursor: pointer;
            }
        }
    }

    .formTips {
        line-height: 1.6;
        font-size: 12px;
        color: #888;
        background-color: #fffaf9;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .toAgreement {
            color: #ff6b00;

            &:hover {
                cursor: pointer;
                color: #f99547;
            }
        }

        .tips_title {
            font-size: 14px;
            color: #ff6b00;
            font-weight: 600;
            margin-bottom: 2px;
        }
    }

    .tips {
        margin-left: 60px;
    }

    .storeTips {
        flex: 1;
    }

    .line {
        width: 0;
        border-left: 1px dashed #eee;
        margin: 0 20px 0 8px;
    }

    .msg {
        flex: 1;
        height: v-bind(height);
        overflow: auto;
        padding-left: 10px;
        box-sizing: border-box;
        padding-right: 36px;

        .title {
            border-left: 3px solid #ff6b00;
            padding-left: 8px;
            margin: 10px 0 24px;
        }

        .sync {
            display: flex;
            align-items: flex-end;
            margin: 18px 0 12px;

            .sync-img {
                background-color: #fff;
                border: 1px solid #eaeaea;
                margin-right: 15px;

                .img-detail {
                    width: 170px;
                    height: 120px;
                }
            }

            .sync-title {
                .title-detail {
                    margin-top: 10px;
                    font-size: 14px;
                    font-weight: 400;
                    color: #33302d;
                    line-height: 14px;
                }
            }
        }
    }

    .finishBox {
        flex: 1;
        height: 500px;
        padding-left: 30px;
        padding-bottom: 100px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & > div {
            line-height: 1;
            font-size: 13px;
            color: #555;
            margin-top: 16px;
        }

        .tag {
            span {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
        }
    }
}

.upload-file-box {
    position: relative;

    .open-img {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 100% 0 0;
        background-color: rgb(51 48 45 / 50%);
        color: white;
        cursor: pointer;
    }
}

.next {
    display: flex;
    justify-content: flex-end;
}

.finished {
    display: flex;
    justify-content: flex-end;
}

.go-auth {
    cursor: pointer;
    color: #ff6b00;
    margin-left: 10px;
}

.auth-tips {
    margin: 25px 0;
}

.color-tips {
    color: #f76c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 2px;
}

.footer_button {
    text-align: center;
    background-color: #fff;
    padding: 16px 24px;
    margin: 0 -16px -16px;
    border-top: 1px solid #eaeaea;
}
</style>
